﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace IronSharePoint.Events
{
    public class IronFeatureReceiver : SPFeatureReceiver
    {
        public IronScriptEngine InitializeScriptEngine(SPFeatureReceiverProperties properties)
        {
            Guid featureId = properties.Definition.Id;
            string scriptPath = properties.Definition.Properties["ScriptPath"].Value;

            IronScriptEngine engine = new IronScriptEngine();
            engine.ScriptResolver.FeatureId = featureId;
            engine.CompileScriptFrom(scriptPath);

            return engine;
        }


        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            IronScriptEngine engine = InitializeScriptEngine(properties);

            if (engine.Scope.ContainsVariable("FeatureActivated"))
            {
                object method = engine.Scope.GetVariable("FeatureActivated");
                engine.Operations.Call(method, properties);
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            IronScriptEngine engine = InitializeScriptEngine(properties);

            if (engine.Scope.ContainsVariable("FeatureDeactivating"))
            {
                object method = engine.Scope.GetVariable("FeatureDeactivating");
                engine.Operations.Call(method, properties);
            }
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
            IronScriptEngine engine = InitializeScriptEngine(properties);

            if (engine.Scope.ContainsVariable("FeatureInstalled"))
            {
                object method = engine.Scope.GetVariable("FeatureInstalled");
                engine.Operations.Call(method, properties);
            }
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            IronScriptEngine engine = InitializeScriptEngine(properties);

            if (engine.Scope.ContainsVariable("FeatureUninstalling"))
            {
                object method = engine.Scope.GetVariable("FeatureUninstalling");
                engine.Operations.Call(method, properties);
            }
        }
    }
}
